package com.notecalendar.quartz;

import java.util.Calendar;

import com.notecalendar.quartz.exception.QuartzCalendarException;

/**
 * Time to execute a quartz task
 * @author angelcereijo
 *
 */
public class QuartzCalendar {
	
	private int minute = 0;
	private int hour = 0;
	private int day = 0;
	private int month = 0;
	private int year = 0;
	
	private Calendar c = Calendar.getInstance();
	
	/**
	 * Constructor
	 * @param year value major or equal than actual year
	 * @param month value between 1 and 12
	 * @param day
	 * @param hour
	 * @param minute
	 * @throws QuartzCalendarException
	 */
	public QuartzCalendar(int year, int month, int day, int hour, int minute) throws QuartzCalendarException{
		setYear(year);
		setMonth(month);
		setDay(day);
		setHour(hour);
		setMinute(minute);
	}
	
	/**
	 * Return the minute, hour, day, month and year like a cron expresion. Ej.: '0 08 13 3 JUL ? 2011'
	 * @return
	 */
	public String getQuartzCronExpresion(){
		//"0 08 13 3 JUL ? 2011"
		String cronExpresion = "0 "+ getMinute()+" "+getHour()+" "+
			getDay()+" "+getMonth()+" ? "+getYear();
		return cronExpresion;
	}
	
	
	public int getMinute() {
		return minute;
	}
	private void setMinute(int minute) throws QuartzCalendarException{
		if(minute<0 || minute>59){
			throw new QuartzCalendarException(QuartzCalendarException.MINUTE_VALUE_EXCEPTION);
		}
		this.minute = minute;
		c.set(Calendar.MINUTE, minute);
	}
	
	public int getHour() {
		return hour;
	}
	private void setHour(int hour) throws QuartzCalendarException{
		if(hour<0 || hour>23){
			throw new QuartzCalendarException(QuartzCalendarException.HOUR_VALUE_EXCEPTION);
		}
		this.hour = hour;
		c.set(Calendar.HOUR_OF_DAY, hour);
	}
	
	public int getDay() {
		return day;
	}
	private void setDay(int day) throws QuartzCalendarException{
		if(day<1 || day>31){
			throw new QuartzCalendarException(QuartzCalendarException.DAY_VALUE_EXCEPTION);
		}
		if(day>c.getActualMaximum(Calendar.DAY_OF_MONTH)){
			throw new QuartzCalendarException(QuartzCalendarException.DAY_MONTH_VALUE_EXCEPTION);
		}
		
		this.day = day;
		c.set(Calendar.DAY_OF_MONTH, day);
	}
	
	public int getMonth() {
		return month;
	}
	private void setMonth(int month) throws QuartzCalendarException{
		if(month<1 || month>12){
			throw new QuartzCalendarException(QuartzCalendarException.MONTH_VALUE_EXCEPTION);
		}
		this.month = month;
		c.set(Calendar.MONTH, month-1);
	}
	
	
	public int getYear() {
		return year;
	}
	private void setYear(int year) throws QuartzCalendarException{
		if(year<c.get(Calendar.YEAR)){
			throw new QuartzCalendarException(QuartzCalendarException.YEAR_VALUE_EXCEPTION);
		}
		this.year = year;
	}
	
	
	
	
}
